import 'package:flutter/material.dart';
import '../utils/responsive_layout.dart';
import '../theme/app_theme.dart';
import 'modern_card.dart';

/**
 * 现代化列表项样式枚举
 */
enum ModernListItemStyle {
  simple,      // 简单样式
  detailed,    // 详细样式
  card,        // 卡片样式
  compact,     // 紧凑样式
}

/**
 * 现代化列表组件
 * 支持多种样式和交互效果
 */
class ModernList<T> extends StatelessWidget {
  final List<T> items;
  final Widget Function(BuildContext context, T item, int index) itemBuilder;
  final Widget Function(BuildContext context, String query)? emptyBuilder;
  final Widget Function(BuildContext context)? loadingBuilder;
  final ScrollController? scrollController;
  final EdgeInsetsGeometry? padding;
  final bool shrinkWrap;
  final ScrollPhysics? physics;
  final bool isLoading;
  final String? emptyMessage;
  final IconData? emptyIcon;
  final VoidCallback? onRefresh;
  final bool showDividers;
  final double? itemSpacing;

  const ModernList({
    super.key,
    required this.items,
    required this.itemBuilder,
    this.emptyBuilder,
    this.loadingBuilder,
    this.scrollController,
    this.padding,
    this.shrinkWrap = false,
    this.physics,
    this.isLoading = false,
    this.emptyMessage,
    this.emptyIcon,
    this.onRefresh,
    this.showDividers = false,
    this.itemSpacing,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);

    if (isLoading) {
      return _buildLoading(context);
    }

    if (items.isEmpty) {
      return _buildEmpty(context);
    }

    Widget listView = ListView.separated(
      controller: scrollController,
      padding: padding ?? EdgeInsets.all(isDesktop ? 16 : 12),
      shrinkWrap: shrinkWrap,
      physics: physics,
      itemCount: items.length,
      separatorBuilder: (context, index) {
        if (showDividers) {
          return Divider(
            height: 1,
            color: colorScheme.outline.withOpacity(0.1),
          );
        }
        return SizedBox(height: itemSpacing ?? (isDesktop ? 8 : 6));
      },
      itemBuilder: (context, index) {
        return itemBuilder(context, items[index], index);
      },
    );

    if (onRefresh != null) {
      return RefreshIndicator(
        onRefresh: () async {
          onRefresh!();
        },
        child: listView,
      );
    }

    return listView;
  }

  /**
   * 构建加载状态
   */
  Widget _buildLoading(BuildContext context) {
    if (loadingBuilder != null) {
      return loadingBuilder!(context);
    }

    return const Center(
      child: CircularProgressIndicator(),
    );
  }

  /**
   * 构建空状态
   */
  Widget _buildEmpty(BuildContext context) {
    if (emptyBuilder != null) {
      return emptyBuilder!(context, '');
    }

    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            emptyIcon ?? Icons.inbox_outlined,
            size: isDesktop ? 64 : 48,
            color: colorScheme.onSurfaceVariant.withOpacity(0.5),
          ),
          SizedBox(height: isDesktop ? 16 : 12),
          Text(
            emptyMessage ?? '暂无数据',
            style: theme.textTheme.bodyLarge?.copyWith(
              color: colorScheme.onSurfaceVariant,
            ),
          ),
        ],
      ),
    );
  }
}

/**
 * 现代化列表项组件
 */
class ModernListItem extends StatefulWidget {
  final Widget? leading;
  final Widget title;
  final Widget? subtitle;
  final Widget? trailing;
  final VoidCallback? onTap;
  final VoidCallback? onLongPress;
  final bool enabled;
  final bool selected;
  final ModernListItemStyle style;
  final EdgeInsetsGeometry? padding;
  final Color? backgroundColor;
  final bool showHoverEffect;

  const ModernListItem({
    super.key,
    this.leading,
    required this.title,
    this.subtitle,
    this.trailing,
    this.onTap,
    this.onLongPress,
    this.enabled = true,
    this.selected = false,
    this.style = ModernListItemStyle.simple,
    this.padding,
    this.backgroundColor,
    this.showHoverEffect = true,
  });

  @override
  State<ModernListItem> createState() => _ModernListItemState();
}

class _ModernListItemState extends State<ModernListItem>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  bool _isHovered = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 150),
      vsync: this,
    );

    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.98,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  /**
   * 处理悬停状态
   */
  void _handleHover(bool isHovered) {
    if (!widget.enabled || !widget.showHoverEffect) return;
    
    setState(() {
      _isHovered = isHovered;
    });
  }

  /**
   * 处理点击状态
   */
  void _handleTap() {
    if (!widget.enabled) return;
    
    _animationController.forward().then((_) {
      _animationController.reverse();
    });
    
    widget.onTap?.call();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);

    Widget content = _buildContent(theme, colorScheme, isDesktop);

    if (widget.style == ModernListItemStyle.card) {
      return AnimatedBuilder(
        animation: _animationController,
        builder: (context, child) {
          return Transform.scale(
            scale: _scaleAnimation.value,
            child: ModernCard(
              onTap: _handleTap,
              onLongPress: widget.onLongPress,
              isSelected: widget.selected,
              isClickable: widget.enabled,
              isHoverable: widget.showHoverEffect,
              child: content,
            ),
          );
        },
      );
    }

    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, child) {
        return Transform.scale(
          scale: _scaleAnimation.value,
          child: MouseRegion(
            onEnter: (_) => _handleHover(true),
            onExit: (_) => _handleHover(false),
            child: GestureDetector(
              onTap: _handleTap,
              onLongPress: widget.onLongPress,
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                padding: widget.padding ?? _getDefaultPadding(isDesktop),
                decoration: _buildDecoration(theme, colorScheme),
                child: content,
              ),
            ),
          ),
        );
      },
    );
  }

  /**
   * 构建内容
   */
  Widget _buildContent(ThemeData theme, ColorScheme colorScheme, bool isDesktop) {
    switch (widget.style) {
      case ModernListItemStyle.simple:
        return _buildSimpleContent(theme, colorScheme, isDesktop);
      case ModernListItemStyle.detailed:
        return _buildDetailedContent(theme, colorScheme, isDesktop);
      case ModernListItemStyle.compact:
        return _buildCompactContent(theme, colorScheme, isDesktop);
      case ModernListItemStyle.card:
        return _buildSimpleContent(theme, colorScheme, isDesktop);
    }
  }

  /**
   * 构建简单内容
   */
  Widget _buildSimpleContent(ThemeData theme, ColorScheme colorScheme, bool isDesktop) {
    return Row(
      children: [
        if (widget.leading != null) ...[
          widget.leading!,
          SizedBox(width: isDesktop ? 16 : 12),
        ],
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              DefaultTextStyle(
                style: theme.textTheme.bodyLarge?.copyWith(
                  color: widget.enabled
                      ? colorScheme.onSurface
                      : colorScheme.onSurface.withOpacity(0.5),
                  fontWeight: widget.selected ? FontWeight.w600 : FontWeight.normal,
                ) ?? const TextStyle(),
                child: widget.title,
              ),
              if (widget.subtitle != null) ...[
                const SizedBox(height: 4),
                DefaultTextStyle(
                  style: theme.textTheme.bodyMedium?.copyWith(
                    color: widget.enabled
                        ? colorScheme.onSurfaceVariant
                        : colorScheme.onSurfaceVariant.withOpacity(0.5),
                  ) ?? const TextStyle(),
                  child: widget.subtitle!,
                ),
              ],
            ],
          ),
        ),
        if (widget.trailing != null) ...[
          SizedBox(width: isDesktop ? 16 : 12),
          widget.trailing!,
        ],
      ],
    );
  }

  /**
   * 构建详细内容
   */
  Widget _buildDetailedContent(ThemeData theme, ColorScheme colorScheme, bool isDesktop) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            if (widget.leading != null) ...[
              widget.leading!,
              SizedBox(width: isDesktop ? 16 : 12),
            ],
            Expanded(
              child: DefaultTextStyle(
                style: theme.textTheme.titleMedium?.copyWith(
                  color: widget.enabled
                      ? colorScheme.onSurface
                      : colorScheme.onSurface.withOpacity(0.5),
                  fontWeight: widget.selected ? FontWeight.w600 : FontWeight.w500,
                ) ?? const TextStyle(),
                child: widget.title,
              ),
            ),
            if (widget.trailing != null) widget.trailing!,
          ],
        ),
        if (widget.subtitle != null) ...[
          SizedBox(height: isDesktop ? 8 : 6),
          DefaultTextStyle(
            style: theme.textTheme.bodyMedium?.copyWith(
              color: widget.enabled
                  ? colorScheme.onSurfaceVariant
                  : colorScheme.onSurfaceVariant.withOpacity(0.5),
              height: 1.4,
            ) ?? const TextStyle(),
            child: widget.subtitle!,
          ),
        ],
      ],
    );
  }

  /**
   * 构建紧凑内容
   */
  Widget _buildCompactContent(ThemeData theme, ColorScheme colorScheme, bool isDesktop) {
    return Row(
      children: [
        if (widget.leading != null) ...[
          widget.leading!,
          SizedBox(width: isDesktop ? 12 : 8),
        ],
        Expanded(
          child: DefaultTextStyle(
            style: theme.textTheme.bodyMedium?.copyWith(
              color: widget.enabled
                  ? colorScheme.onSurface
                  : colorScheme.onSurface.withOpacity(0.5),
              fontWeight: widget.selected ? FontWeight.w600 : FontWeight.normal,
            ) ?? const TextStyle(),
            child: widget.title,
          ),
        ),
        if (widget.trailing != null) ...[
          SizedBox(width: isDesktop ? 12 : 8),
          widget.trailing!,
        ],
      ],
    );
  }

  /**
   * 获取默认内边距
   */
  EdgeInsetsGeometry _getDefaultPadding(bool isDesktop) {
    switch (widget.style) {
      case ModernListItemStyle.simple:
        return EdgeInsets.symmetric(
          horizontal: isDesktop ? 16 : 12,
          vertical: isDesktop ? 12 : 10,
        );
      case ModernListItemStyle.detailed:
        return EdgeInsets.symmetric(
          horizontal: isDesktop ? 16 : 12,
          vertical: isDesktop ? 16 : 12,
        );
      case ModernListItemStyle.compact:
        return EdgeInsets.symmetric(
          horizontal: isDesktop ? 16 : 12,
          vertical: isDesktop ? 8 : 6,
        );
      case ModernListItemStyle.card:
        return EdgeInsets.zero;
    }
  }

  /**
   * 构建装饰样式
   */
  BoxDecoration _buildDecoration(ThemeData theme, ColorScheme colorScheme) {
    Color backgroundColor = widget.backgroundColor ?? Colors.transparent;
    
    if (widget.selected) {
      backgroundColor = colorScheme.primaryContainer.withOpacity(0.3);
    } else if (_isHovered && widget.showHoverEffect) {
      backgroundColor = colorScheme.surfaceVariant.withOpacity(0.5);
    }

    return BoxDecoration(
      color: backgroundColor,
      borderRadius: BorderRadius.circular(8),
    );
  }
}

/**
 * 现代化分组列表组件
 */
class ModernGroupedList<T, G> extends StatelessWidget {
  final List<T> items;
  final G Function(T item) groupBy;
  final Widget Function(BuildContext context, G group) groupHeaderBuilder;
  final Widget Function(BuildContext context, T item, int index) itemBuilder;
  final Widget Function(BuildContext context)? emptyBuilder;
  final ScrollController? scrollController;
  final EdgeInsetsGeometry? padding;
  final bool shrinkWrap;
  final ScrollPhysics? physics;
  final bool showGroupDividers;

  const ModernGroupedList({
    super.key,
    required this.items,
    required this.groupBy,
    required this.groupHeaderBuilder,
    required this.itemBuilder,
    this.emptyBuilder,
    this.scrollController,
    this.padding,
    this.shrinkWrap = false,
    this.physics,
    this.showGroupDividers = true,
  });

  @override
  Widget build(BuildContext context) {
    if (items.isEmpty) {
      return emptyBuilder?.call(context) ?? const SizedBox.shrink();
    }

    // 按组分组
    final Map<G, List<T>> groupedItems = {};
    for (final item in items) {
      final group = groupBy(item);
      groupedItems.putIfAbsent(group, () => []).add(item);
    }

    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);

    return ListView.builder(
      controller: scrollController,
      padding: padding ?? EdgeInsets.all(isDesktop ? 16 : 12),
      shrinkWrap: shrinkWrap,
      physics: physics,
      itemCount: groupedItems.length,
      itemBuilder: (context, groupIndex) {
        final group = groupedItems.keys.elementAt(groupIndex);
        final groupItems = groupedItems[group]!;

        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 组标题
            Padding(
              padding: EdgeInsets.only(
                bottom: isDesktop ? 8 : 6,
                top: groupIndex > 0 ? (isDesktop ? 24 : 20) : 0,
              ),
              child: groupHeaderBuilder(context, group),
            ),
            
            // 组项目
            ...groupItems.asMap().entries.map((entry) {
              final itemIndex = entry.key;
              final item = entry.value;
              
              return Padding(
                padding: EdgeInsets.only(
                  bottom: itemIndex < groupItems.length - 1 
                      ? (isDesktop ? 4 : 3) 
                      : 0,
                ),
                child: itemBuilder(context, item, itemIndex),
              );
            }),
            
            // 组分隔线
            if (showGroupDividers && groupIndex < groupedItems.length - 1)
              Padding(
                padding: EdgeInsets.only(top: isDesktop ? 16 : 12),
                child: Divider(
                  color: colorScheme.outline.withOpacity(0.1),
                ),
              ),
          ],
        );
      },
    );
  }
}